package com.lhc.nacosprovider.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.lang.tree.parser.NodeParser;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhc.nacosprovider.entity.Menu;
import com.lhc.nacosprovider.entity.Order;
import com.lhc.nacosprovider.fegin.StockClient;
import com.lhc.nacosprovider.mapper.MenuMapper;
import com.lhc.nacosprovider.mapper.OrderMapper;
import com.lhc.nacosprovider.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * @author liuchaoqun
 * @date 2022/6/17
 * @Description 菜单
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    StockClient stockClient;

    @Override
    public List<Menu> allMenus() {
        return menuMapper.allMenu();
    }

    @Override
    public List<Tree<String>> getTreeNode() {
        List<Menu> menus = menuMapper.allMenu();

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setNameKey("name");

        List<Tree<String>> treeList = TreeUtil.build(menus, "0", treeNodeConfig, (menu, tree) -> {
            tree.setId(menu.getId().toString());
            tree.setParentId(menu.getParentId().toString());
            tree.setName(menu.getName());
        });

        return treeList;
    }

    @Override
    public String create(Long id) {
        Menu menu = menuMapper.selectById(id);

        Order order = new Order();
        order.setOrderName(menu.getName());

        orderMapper.insert(order);

        // fegin 调用扣减库存
        stockClient.reduce(id);
        return "成功创建了一个" + menu.getName() + "的订单";
    }
}
